# backend/crud/library_crud.py
from sqlalchemy.orm import Session
from backend.models import Library, LibraryMember
import random
import string


def create_library(db: Session, name: str, owner_id: int):
    # 生成唯一邀请码
    invite_code = ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))

    db_library = Library(
        name=name,
        invite_code=invite_code,
        owner_id=owner_id,
        created_at=datetime.utcnow(),
        is_active=True
    )
    db.add(db_library)
    db.commit()
    db.refresh(db_library)

    # 添加创建者为书阁所有者
    add_member(db, db_library.id, owner_id, is_owner=True)

    return db_library


def get_library(db: Session, library_id: int):
    return db.query(Library).filter(Library.id == library_id).first()


def get_library_by_invite_code(db: Session, invite_code: str):
    return db.query(Library).filter(Library.invite_code == invite_code).first()


def add_member(db: Session, library_id: int, user_id: int, is_owner: bool = False):
    db_member = LibraryMember(
        library_id=library_id,
        user_id=user_id,
        is_owner=is_owner,
        join_date=datetime.utcnow()
    )
    db.add(db_member)
    db.commit()
    db.refresh(db_member)
    return db_member


def deactivate_library(db: Session, library_id: int):
    db_library = get_library(db, library_id)
    if db_library:
        db_library.is_active = False
        db.commit()
        db.refresh(db_library)
    return db_library
